﻿#include "klinedatafetcher.h"
#include <QUrlQuery>
#include <QDebug> // 添加 QDebug 以便打印日志
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QDateTime>

KLineDataFetcher::KLineDataFetcher(QObject *parent)
    : QObject(parent), networkManager(new QNetworkAccessManager(this))
{
    connect(networkManager, &QNetworkAccessManager::finished, this, &KLineDataFetcher::onReplyFinished);
}

void KLineDataFetcher::fetchKLineData(const QString &token, const QString &code,
                                      const QString &klineType) {
  // 设置基础 URL
  QString baseUrl = "https://quote.alltick.io/quote-b-api/kline";

  // 设置 URL 参数
  QUrlQuery urlQuery;
  urlQuery.addQueryItem("token", token);

  // 设置 query 参数
  QString query =
      QString("{\"data\":{\"code\":\"%1\",\"kline_type\":\"%2\",\"kline_"
              "timestamp_end\":\"0\",\"query_kline_num\":\"1\",\"adjust_type\":"
              "\"0\"},\"trace\":\"116758e0-1b54-49b5-a850-0227e227c2db\"}")
          .arg(code, klineType);

  // 构建完整的 URL
  QUrl url(baseUrl);
  urlQuery.addQueryItem("query", query);
  url.setQuery(urlQuery);

  // 发起网络请求
  QNetworkRequest request(url);
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  networkManager->get(request);
}

void KLineDataFetcher::onReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        emit fetchFailed(reply->errorString());
        reply->deleteLater();
        return;
    }

    QByteArray responseData = reply->readAll();
    qDebug() << "Raw Response Data:" << responseData;

    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
    QVector<KLineData> klineDataList;

    if (jsonDoc.isObject()) {
        QJsonObject rootObj = jsonDoc.object();
        QJsonObject dataObj = rootObj.value("data").toObject();
        QJsonArray klineArray = dataObj.value("kline_list").toArray();

        for (const QJsonValue &value : klineArray) {
            QJsonObject klineObj = value.toObject();
            KLineData data;
            data.timestamp = klineObj.value("timestamp").toVariant().toLongLong(); // 解析为 qint64
            data.openPrice = klineObj.value("open_price").toString().toDouble();
            data.closePrice = klineObj.value("close_price").toString().toDouble();
            data.highPrice = klineObj.value("high_price").toString().toDouble();
            data.lowPrice = klineObj.value("low_price").toString().toDouble();
            data.volume = klineObj.value("volume").toString().toDouble();
            data.turnover = klineObj.value("turnover").toString().toDouble();

            // 打印可读的时间格式
            QDateTime dateTime = QDateTime::fromSecsSinceEpoch(data.timestamp);
            qDebug() << "Timestamp:" << data.timestamp << "Readable Time:" << dateTime.toString(Qt::ISODate);

            klineDataList.append(data);
        }
    }

    emit kLineDataFetched(klineDataList);
    reply->deleteLater();
}

QVector<KLineData> KLineDataFetcher::loadKLineDataFromFile(const QString &filePath)
{
    QVector<KLineData> klineDataList;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open file:" << filePath;
        return klineDataList;
    }

    QByteArray fileData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(fileData);
    if (!jsonDoc.isObject()) {
        qDebug() << "Invalid JSON format in file:" << filePath;
        return klineDataList;
    }

    QJsonObject rootObj = jsonDoc.object();
    QJsonObject dataObj = rootObj.value("data").toObject();
    QJsonArray klineArray = dataObj.value("kline_list").toArray();

    for (const QJsonValue &value : klineArray) {
        QJsonObject klineObj = value.toObject();
        KLineData data;
        data.timestamp = klineObj.value("timestamp").toVariant().toLongLong();
        data.openPrice = klineObj.value("open_price").toString().toDouble();
        data.closePrice = klineObj.value("close_price").toString().toDouble();
        data.highPrice = klineObj.value("high_price").toString().toDouble();
        data.lowPrice = klineObj.value("low_price").toString().toDouble();
        data.volume = klineObj.value("volume").toString().toDouble();
        data.turnover = klineObj.value("turnover").toString().toDouble();
        klineDataList.append(data);
    }

    return klineDataList;
}
